"""
@author: 江同学呀
@file: logger.py
@date: 2023/8/22 19:45
@desc:
"""
import sys
from typing import Set, Literal

import loguru

TRACE: str = "TRACE"
DEBUG: str = "DEBUG"
INFOR: str = "INFOR"
CONFIRM: str = "CONFIRM"
QUITE: str = "QUITE"
ALERT: str = "ALERT"
ERROR: str = "ERROR"
MISINFORM: str = "MISINFORM"
NONES: str = "NONES"
FAILS: str = "FAILS"

level_set: Set[str] = {TRACE, DEBUG, INFOR, CONFIRM, QUITE, ALERT, ERROR, MISINFORM, NONES, FAILS}
LOGGER_LEVEL = Literal[
    "TRACE", "DEBUG", "INFOR", "CONFIRM", "QUITE", "ALERT", "ERROR", "MISINFORM", "NONES", "FAILS"
]
ES_PC_LOGGER: str = "es_pc_logger"


class Logger:
    _instance = None
    _logger: loguru.logger = None

    def __init__(self):
        return

    def __new__(cls, *args, **kwargs):
        if not isinstance(cls._instance, cls):
            cls._instance = super().__new__(cls)
        return cls._instance

    def init_logger(self, level: LOGGER_LEVEL = ERROR):
        """
        初始化日志记录器
        :param level:
        :return:
        """
        if not level or level not in level_set:
            level: str = ERROR
        log_format: str = (
            "<light-green>{time:YYYY-MM-DD HH:mm:ss,SSS}</light-green> [<level>{level: <5}</level>] "
            "<cyan>{process.name}({process.id})</cyan>:<cyan>{thread.name: <18}({thread.id: <5})</cyan>"
            " | <blue>{module}</blue>.<blue>{function}</blue>:<blue>{line}</blue> - "
            "<level>{message}</level>"
        )
        # noinspection PyTypeChecker
        loguru.logger.add(
            # lambda msg: None,
            sys.stderr,
            format=log_format,
            filter=lambda record: "name" in record["extra"] and record["extra"]["name"] == ES_PC_LOGGER,
            # rotation="00:00",
            level=level,
            enqueue=False,
            backtrace=True,
            diagnose=True,
        )
        self._logger: loguru.logger = loguru.logger.bind(name=ES_PC_LOGGER)
        return

    def info(self, msg: str, *args, **kwargs) -> loguru.logger:
        return self._logger.debug(msg, *args, **kwargs)

    def exception(self, msg: str, *args, **kwargs) -> loguru.logger:
        return self._logger.opt(exception=True).error(msg, *args, **kwargs)

    def error(self, msg: str, *args, **kwargs) -> loguru.logger:
        return self._logger.error(msg, *args, **kwargs)

    def warning(self, msg: str, *args, **kwargs) -> loguru.logger:
        return self._logger.warning(msg, *args, **kwargs)


logger: Logger = Logger()
